package br.com.trumah.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.trumah.dao.interfaces.EnderecoDAO;
import br.com.trumah.model.Endereco;
import br.com.trumah.utils.HibernateUtil;

public class EnderecoDAOImpl implements EnderecoDAO {

	private Session session = null;
	private Transaction t = null;
	
	@Override
	public void salvar(Endereco endereco) {

		try{

			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			session.save(endereco);
			t.commit();
			
		} catch (HibernateException ex) {
			
			t.rollback();
			ex.printStackTrace();
		} finally {
			
			session.close();
			
		}

	}

	@Override
	public Endereco obterEndereco(long id) {
		
		Endereco endereco = null;
		
		try {

			session = HibernateUtil.getSessionFactory().openSession();
			endereco = (Endereco) session.load(Endereco.class, id);
			
		} catch (HibernateException ex){
			ex.printStackTrace();
		} finally {
			session.close();
		}

		return endereco;
		
	}

	@Override
	public List<Endereco> listar() {

		List<Endereco> lista = null;
		
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			lista = session.createQuery("from Endereco").list();
			t.commit();
			
		} catch (HibernateException ex) {
			
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}

		return lista;
		
	}

	@Override
	public void remover(Endereco endereco) {

		try {

			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			session.delete(endereco);
			t.commit();
			
		} catch (HibernateException ex) {
			
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}

	}

	@Override
	public void atualizar(Endereco endereco) {
		
		try {

			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			session.update(endereco);
			t.commit();
			
		} catch (HibernateException ex) {
			
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}

	}

}
